# -*- coding: utf-8 -*-
from google.appengine.ext import ndb
from DB.DB_Classes import *
import datetime
from django.utils import simplejson

YEAR = "2014"
SEMESTER_DATA ='SemesterData'
FACULTY_FOR_SEM = 'FacultyForSem'

def getAllCoursesOfSem(currSemester):
    sem = ndb.Key(SEMESTER_DATA, YEAR + currSemester).get()
    return simplejson.dumps({"Courses" : sem.courses_list})

def getFaculties(currSemester):
    sem = ndb.Key(SEMESTER_DATA, YEAR + currSemester).get()
    return simplejson.dumps({"faculties" : sem.faculties})
                              
def getCoursesListByFaculty(currSemester, fac_num):
    coursesList = []
    fac = ndb.Key(FACULTY_FOR_SEM, YEAR + currSemester + '_' + fac_num).get()
    
    for course in fac.courses:
            coursesList.append({'course_name': course['course_name'], 'course_num': course['course_num']})
    
    jsonCoursesList = simplejson.dumps({
            "courses"  : coursesList
    })
     
    return jsonCoursesList
    
# The groups (01,02,03) will be ordered in increasing order
def getChosenCoursesInfo(currSemester,chosenCoursesList):

    coursesList = []
    for curr_course in chosenCoursesList:
        fac = ndb.Key(FACULTY_FOR_SEM, YEAR + currSemester + '_' + curr_course[:2]).get()
        course = fac.courses.get(curr_course)
        coursesList.append(course)
            
    jsonCoursesInfo = simplejson.dumps({
            "coursesInfo"  : coursesList
    })
    return jsonCoursesInfo
                 
def getCourseProfileInformationFromModels(currSemester,fac_num, courseNum):
    fac = ndb.Key(FACULTY_FOR_SEM, YEAR + currSemester + '_' + fac_num).get()
    jsonCourseInfo = simplejson.dumps({
            "courseInfo"  : [fac.courses.get(courseNum)]
    })
    return jsonCourseInfo
    

def getCourseSyllabus(currSemester,facourse_num, courseNum):
    fac = ndb.Key(FACULTY_FOR_SEM, YEAR + currSemester + '_' + facourse_num).get()
    course = fac.courses.get(courseNum)
    return course["course_syllabus"]

def saveUserData(userId, userEmail, nickName,info,semesterToSave,chosenCoursesLists):
    user = ndb.Key('User', userid).get()

    if user is None:
        if sem == 0:
            to_put =   {'displaySettingsArr' : [info['displaySettingsArr'][0],{}], 'coursesInfoArr' : [info['coursesInfoArr'][0],[]]}
        if sem == 1:
            to_put =   {'displaySettingsArr' : [{},info['displaySettingsArr'][1]], 'coursesInfoArr' : [[],info['coursesInfoArr'][1]]}
        if sem == 2:
            to_put =   {'displaySettingsArr' : [info['displaySettingsArr'][0],info['displaySettingsArr'][1]], 'coursesInfoArr' : [info['coursesInfoArr'][0],info['coursesInfoArr'][1]]}
        user = n_User(id = userid, userId = userid , userEmail = email, nickName = nick, saved_data = {YEAR:to_put}, chosenCoursesLists = {YEAR:[[],[]]})
    else:
        if user.saved_data.get(YEAR) is None:
            user.saved_data[YEAR] =  {'displaySettingsArr' : [{},{}], 'coursesInfoArr' : [[],[]]}
        if sem == 0:
            user.saved_data[YEAR]['displaySettingsArr'][0] = info['displaySettingsArr'][0]
            user.saved_data[YEAR]['coursesInfoArr'][0] = info['coursesInfoArr'][0]
        if sem == 1:
            user.saved_data[YEAR]['displaySettingsArr'][1] = info['displaySettingsArr'][1]
            user.saved_data[YEAR]['coursesInfoArr'][1] = info['coursesInfoArr'][1]
        if sem == 2:
            user.saved_data[YEAR]['displaySettingsArr'][0] = info['displaySettingsArr'][0]
            user.saved_data[YEAR]['coursesInfoArr'][0] = info['coursesInfoArr'][0]
            user.saved_data[YEAR]['displaySettingsArr'][1] = info['displaySettingsArr'][1]
            user.saved_data[YEAR]['coursesInfoArr'][1] = info['coursesInfoArr'][1]
    
    #old_courses = user.chosenCoursesLists
    old_courses = user.chosenCoursesLists.get(YEAR)
    if old_courses is None:
        to_delete_A = []
        to_delete_B = []
        to_add_A = set(courses[0])
        to_add_B = set(courses[1])
    
    else:
        to_delete_A = set(old_courses[0]) - set(courses[0])
        to_delete_B = set(old_courses[1]) - set(courses[1])
        to_add_A = set(courses[0]) - set(old_courses[0])
        to_add_B = set(courses[1]) - set(old_courses[1])
    
    if len(to_delete_A) > 0:
        delete_user_from_course(YEAR, "1", userid, to_delete_A)
    if len(to_delete_B) > 0:
        delete_user_from_course(YEAR, "2", userid, to_delete_B)
    if len(to_add_A) > 0:
        add_user_to_course(YEAR, "1", userid, to_add_A)
    if len(to_add_B) > 0:
        add_user_to_course(YEAR, "2", userid, to_add_B)
    
    user.chosenCoursesLists[YEAR] = courses
    return user.put()

def loadUserData(userID, userEmail, nickName):
    
    user = ndb.Key('User', userID).get()

    if user is None:
        user = User(id = userID ,userId = userID , userEmail = userEmail, nickName = nickName,saved_data = {YEAR:{'displaySettingsArr' : [{},{}], 'coursesInfoArr' : [[],[]]}})
        user.put()    
    for course in user.saved_data.get(YEAR)['coursesInfoArr'][0]:
        fac = ndb.Key(FACULTY_FOR_SEM, YEAR + "01" +'_'+ course['course_num'][:2]).get()
        curr_course = fac.courses.get(course['course_num'])
        if curr_course is None:
            user.saved_data.get(YEAR)['coursesInfoArr'][0].remove(course)
        else:
            course["course_points"] = curr_course["course_points"]
            course['course_group'] = curr_course['course_group'] ##########################################
            
    for course in user.saved_data.get(get_year)['coursesInfoArr'][1]:
        fac = ndb.Key(FACULTY_FOR_SEM, YEAR + "02" +'_'+ course['course_num'][:2]).get()
        curr_course = fac.courses.get(course['course_num'])
        if curr_course is None:
            user.saved_data.get(YEAR)['coursesInfoArr'][1].remove(course)
        else:
            course["course_points"] = curr_course["course_points"]
            course['course_group'] = curr_course['course_group'] ##########################################
            
    return simplejson.dumps(user.saved_data.get(YEAR))

def getFriendList(currSemester,facourse_num,courseNum,friends):
    overallData = OverallData.get_by_id('1')
    course_stats = ndb.Key('CoursesStats',YEAR + currSemester).get()
    
    if course_stats is None:
        return [[],0]
    students_list = course_stats.stats.get(courseNum)
    if students_list is None:
        return [[],0]
    friends_in_course = []
    for friend in friends:
        google_id = overallData.facebook_to_google_map.get(friend["id"])
        if google_id is None:
            continue
        if students_list.__contains__(google_id):
            friends_in_course.append(friend)

    return simplejson.dumps({'friendsList': friends_in_course, 'totalCourseSelected': len(students_list)})

def getFriendChosenCourses(userFacebookId):
    overallData = OverallData.get_by_id('1')
    
    gID = overallData.facebook_to_google_map.get(userFacebookId)
    user = ndb.Key('User', gID).get()

    return simplejson.dumps({'friendCourses': user.saved_data[YEAR]['displaySettingsArr']})
    
@ndb.transactional
def saveFBGoogle(fbID, googleID):
    overallData = OverallData.get_by_id('1')
    overallData.facebook_to_google_map[fbID] = googleID
    return overallData.put()

#get the data structure of event links of the user
def getEventsToDelete(userId):
    user = ndb.Key('User', userId).get()
    if user is None:
        return [[],[],[]]
    return user.events

#save new event links data structure of the user
def saveEventsSynced(userId, eventLinkList, userEmail, userNickname):
    user = ndb.Key('User', userId).get()

    if user is None:
        user = n_User(id= userId,userId = userId , userEmail = userEmail,nickName = userNickname, saved_data = {YEAR:{'displaySettingsArr' : [{},{}], 'coursesInfoArr' : [[],[]]}})
    user.events = eventLinkList
    return user.put()

@ndb.transactional
def delete_user_from_course(get_year,currSemester,userid,courses_to_del):
    course_stats = ndb.Key('CoursesStats',get_year + str(currSemester)).get()
    if course_stats is None:
        return
    is_changed = False
    for course_to_del in courses_to_del:
        students_list = course_stats.stats.get(course_to_del)
        if students_list is not None and students_list.__contains__(userid):
            students_list.remove(userid)
            is_changed = True
    if is_changed:
        course_stats.put()

@ndb.transactional(xg=True)
def add_user_to_course(get_year,currSemester,userid,courses_to_add):
    
    course_stats = ndb.Key('CoursesStats',get_year + str(currSemester)).get()
    if course_stats is None:
        course_stats = CoursesStats(id = get_year + str(currSemester), semester = get_year + currSemester)
    is_changed = False
    for course_to_add in courses_to_add:
        students_list = course_stats.stats.get(course_to_add)
        if students_list is None:
            students_list = [userid]
            is_changed = True
        elif not students_list.__contains__(userid):
            students_list.append(userid)
            is_changed = True
        else:
            continue
        course_stats.stats[course_to_add] = students_list
    if is_changed:
        course_stats.put()
    